from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
import simplejson as json

class GetAll(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        ingredients = db.GqlQuery("SELECT * from Ingredient")
        result = [{'name': str(ingredient.name), 'key': str(ingredient.key())} for ingredient in ingredients]
        self.response.out.write(json.dumps(result))
        
class GetKeyByName(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write("in GET");
            
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain'
        ingredientName = self.request.get("ingredientName");
        query = db.GqlQuery("SELECT __key__ FROM Ingredient WHERE name = :1 LIMIT 1", ingredientName);
        if query.count(1) != 0:
            self.response.out.write(query[0]);
        else:
            self.response.out.write("Not found");
        
application = webapp.WSGIApplication([('/ingredients/all', GetAll), ('/ingredients/get_key', GetKeyByName)], debug=True)
  
def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()